package com.example.service.impl;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.example.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dao.ProjectInfoMapper;
import com.example.dao.UxJbcardMapper;
import com.example.dao.UxenglstMapper;
import com.example.dao.UxpmStckMapper;
import com.example.dao.UxtpMapper;
import com.example.dao.UxmadsMapper;
import com.example.exchange.BPWebService;
import com.example.exchange.MapUtils;
import com.example.exchange.ServiceUtil;
import com.example.exchange.XMLHeaderConstants;
import com.example.util.XMLResUtil;
import com.example.service.AutoJobcArdServer;



import net.sf.json.JSONObject;

import com.example.exchange.UnifierWebServicesUfbs;

@Service
public class AutoJobcArdARServerImpl extends Util implements AutoJobcArdServer {

	@Autowired
	private UxenglstMapper uxenglstMapper;
	@Autowired
	private UxpmStckMapper uxpmStckMapper;
	@Autowired
	private UxJbcardMapper uxJbcardMapper;
	@Autowired
	private ProjectInfoMapper projectInfoMapper;
	@Autowired
	private UxtpMapper uxtpMapper;
	@Autowired
	private UxmadsMapper uxmadsMapper;

	/**
	 * AR物料缺失追踪
	 *
	 * @throws IOException
	 */
	public void auto_synchro_UXMMT_AR() throws IOException {

		List<Map<String, String>> list = uxJbcardMapper.select_Jbcard_Material_Part_AR(); // 查询出构件中的零件与母材在即时库存中为0的

//		if (list.size() != 0) {
//			uxJbcardMapper.delete_uxdram();
//			uxJbcardMapper.delete_uxdram_PERM();
//
		Set<String> DrawingSet = new HashSet<String>();
//
			List<Map<String, String>> list2 = uxJbcardMapper.select_Jbcard_Material_CUT();// 查询出目前下切缺母材的 需产生的零件编码
//
//			// 为预制Jobcard 匹配到相关的安装Jobcard
//			List<Map<String, String>> list3 = uxJbcardMapper.select_Jbcard_Material_Fabrication_PI();
//			for (Map<String, String> index : list) {
//				for (Map<String, String> index2 : list3) {
//					if (index.get("DRAWING_NO").equals(index2.get("MATERIAL_CODE"))) {// 业务构件编号 就是构件图
//						index.put("JOBCARD_INSTALL_NO", index2.get("DRAWING_NO"));
//						index.put("REV_2", index2.get("DRAWING_VERSION"));
//					}
//				}
//
//			}
			// 查询安装Jobcard 所缺的母材
			List<Map<String, String>> list4 = uxJbcardMapper.select_Jbcard_Material_MATERIAL_AR();
			for (Map<String, String> index : list4) {
				System.err.println(list4);
				DrawingSet.add(index.get("DRAWING_NO"));// 筛入缺母材，相关MTO
			}
			list.addAll(list4);
			// 查询构件缺母材的
			List<Map<String, String>> list5 = uxJbcardMapper.select_Jbcard_Material_Bulk_AR();
			for (Map<String, String> index : list5) {
				DrawingSet.add(index.get("DRAWING_NO"));// 筛入缺母材，相关MTO
			}
			list.addAll(list5);

			List<Map<String, String>> listMto = null;
			if (DrawingSet.size() > 0) {
				listMto = uxJbcardMapper.select_Jbcard_Material_MTO(DrawingSet);
				for (Map<String, String> index : list) {
					for (Map<String, String> index2 : listMto) {
						String DRAWING_NO = index.get("JOBCard_No_1");
						String REV = index.get("Rev_1");
						if (index2.get("DRAWING_NO").equals(DRAWING_NO) && index2.get("REV").equals(REV)) {
							index.put("MATERIAL_NAME", index2.get("MATERIAL_NAME"));
							index.put("MTO_NO", index2.get("MTO_NO"));
							index.put("TECHNICAL_REQUIREMENT", index2.get("TECHNICAL_REQUIREMENT"));
							System.err.println(index);
						}
					}
				}
			}

			for (int i = 0; i < list.size() / 500 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
				List<Map<String, String>> index = new ArrayList<Map<String, String>>();
				if ((i + 1) * 500 > list.size())
					index = list.subList(i * 500, list.size());
				if ((i + 1) * 500 <= list.size())
					index = list.subList(i * 500, (i + 1) * 500);
				if (index.size() != 0) {
					Integer id = uxJbcardMapper.select_uxdram_MaxID();
					if (id == null) {
						id = 1;
					} else {
						id++;
					}
					uxJbcardMapper.INSERT_uxdram(list, id);
					uxJbcardMapper.INSERT_uxdram_PERM(list, id);
				}
			}

		//}

	}

	/**
	 * 自动生成舾装专业Jobcard
	 */
	public void auto_GenerateJobcard_AR() throws IOException {
		// 1-查询符合条件的图纸（列表）,每次取单个图纸

		JOBCard jobcard = null;
		ProjectShell project = null;
		List<SchedulePlanEngineering> list = uxenglstMapper.selectUxenglstJobcArdAR();// 查询满足条件的图纸
		for (SchedulePlanEngineering index : list) {
			// System.err.println(index.getDrawing_No() + "-----" +
			// index.getRev());
			// 2-创建一个JOBCard空记录
			jobcard = new JOBCard();
			// 3-取BP自带项目信息CODE & NAME
			// 原DRAW包括项目信息，后取消两要素，WEBSERVICE 方法直接输入Project_ID
			project = projectInfoMapper.select_ProjectShellDetail(index.getProject_id());
			// 赋值JB 编号，对应合同号，业主
			jobcard.setContract_No(project.getContractNo()); // 合同号
			jobcard.setClient(project.getClient());// 客户
			// 赋值JB 模块号，专业，工序，工作车间 ,工作包号
			jobcard.setWork_Package_No(index.getWork_Package_No());
			jobcard.setModule_Number(index.getModule_Name());
			jobcard.setDiscipline(index.getDiscipline());
			jobcard.setWork_Location(jobcard.getDiscipline() + " Workshop");
			// 更新图纸及版本信息
			jobcard.setDrawing_No(index.getDrawing_No());
			jobcard.setDrawing_Name(jobcard.getDrawing_No());
			jobcard.setDrawing_Version(index.getRev());
			jobcard.setRev(index.getRev());
			jobcard.setTest_Package_No(index.getTest_Package_No());
			// 根据jobcard的图纸代码规则从获取JOBCard-Nesting图纸匹配的作业活动
			// Map<String, Object > p6Data =
			// uxJbcardMapper.getP6ScheduleL5Activity(jobcard.getDrawing_No()); //
			// 目前计划与图纸未关联上
			// 下切，组对和焊接分别对应三种不同的情况


			if (index.getDrawing_Category().equals("shopDrawing")) { // 图纸类型是 加设图图类型的话 加设图
				// 查询物料库存即时库存数据
				// 根据draw（套料图含图纸编号和版本）找到母材，关联即时库存表进而查询得到
				List<RequiredMaterialDetail> requiredMaterials = new ArrayList<RequiredMaterialDetail>();
				//List<SurplusMaterial> surplusMaterials = new ArrayList<SurplusMaterial>();

				requiredMaterials = uxpmStckMapper.selectUxpmstck_Drawing_No_bulk(index.getDrawing_No(),
						index.getRev(), project.getProjectObjectid()); // 查询母材
				// 根据上述数量计算当前材料 准备进展%
				jobcard.setMaterial_Progress("0%");
				jobcard.setMaterial_Status("Preparing");
			}
				jobcard.setJOBCard_No(index.getModule_Name() + "-" + index.getWork_Package_No() + "-AR" + "-MAC");
			List<RequiredMaterialDetail> requiredMaterials = new ArrayList<RequiredMaterialDetail>();
			//List<SurplusMaterial> surplusMaterials = new ArrayList<SurplusMaterial>();

			requiredMaterials = uxpmStckMapper.selectUxpmstck_Drawing_No_bulk(index.getDrawing_No(),
					index.getRev(), index.getProject_id()); // 查询母材

			jobcard.setMaterial_Progress("0%");
			jobcard.setMaterial_Status("Preparing");

			insertJobcArdAR(project.getProjectNumber(), index, jobcard, null, requiredMaterials,
					null, null, null);// 创建JobcArd
    }

}





	/**
	 * 自动生成管线专业预工作包
	 *
	 * @throws IOException
	 */
	public void auto_PreWorkPackageAR() throws IOException {

		List<Map<String, String>> projectInfos = projectInfoMapper.select_ProjectID_Number();

		for (Map<String, String> project : projectInfos) {

			String projectCode = project.get("PROJECTNUMBER");

			Object objectPID = project.get("PID");

			Integer projectNumber = Integer.valueOf(String.valueOf(objectPID));

			List<String> ModuleNames = projectInfoMapper.select_ModuleName(projectNumber, "AR");// 查出有多少模块

			for (String Module : ModuleNames) { // 遍历项目下所有模块

				List<String> gradeTypes = uxJbcardMapper.select_WeIdListAR_Dia_Inch_Grade(projectNumber, Module); // 查出一共有多少物料类型每种生成一个试压包

				for (String type : gradeTypes) {// 遍历模块下所有材质类型
					double num = 0;
					List<PreWorkPackageDrawings> drawings = new ArrayList<PreWorkPackageDrawings>();

					List<PreWorkPackageDrawings> datas = uxJbcardMapper.select_WeIdListAR_Dia_Inch(projectNumber,
							Module, type); // 查出某模块某材质没有预工作包未备料的所有Spool
					for (PreWorkPackageDrawings index : datas) {
						num = num + Double.valueOf(index.getDia_Inch());
						drawings.add(index);

						if (num >= 1200) {

//							// 查出次工作包详细零件信息
//							List<PreWorkPackageParts> preWorkPackageParts = uxpmStckMapper
//									.selectUxpmstck_DrawingNoList(drawings, projectNumber);

							boolean is = false;
							List<Map<String, String>> materials = null;
							List<PreWorkPackageMaterialTheoreticalUseQuantity> material_quantitys = null;

							// 查询所需管件数量与库存数量
							List<PreWorkPackageMaterialTheoreticalUseQuantity> pipeFittingsMaterials = uxpmStckMapper
									.selectUxpmstck_DrawingNoList_material_quantity2(drawings, projectNumber);

							// 判断库存是否满足
							for (PreWorkPackageMaterialTheoreticalUseQuantity materialIndex : pipeFittingsMaterials) {
								if (Double.valueOf(materialIndex.getActive_QTY()) >= Double
										.valueOf(materialIndex.getQuantity())) {
									is = true;
								} else {
									is = false;
								}
							}

							if (is) {

								// 查询此工作包使用管子的总母材长度
								material_quantitys = uxpmStckMapper
										.selectUxpmstck_DrawingNoList_material_quantity(drawings, projectNumber);// 查询工作包下零件使用长度

								materials = uxpmStckMapper.select_bulk_ACTIVE_QTY(material_quantitys, projectNumber); // 查出库存拥有母材数量

								for (PreWorkPackageMaterialTheoreticalUseQuantity material : material_quantitys) {// 锁即时库存的母材
									// 优化到备料锁料环境

									material.setQuantity(Double.valueOf(material.getQuantity())
											+ (Double.valueOf(material.getQuantity()) * 0.2) + "");

									for (Map<String, String> map : materials) {
										if (material.getMaterial_Code().equals(map.get("MATERIAL_CODE"))) {
											Object ACTIVE_QTY = map.get("ACTIVE_QTY");
											if (Double.valueOf(material.getQuantity()) <= Double
													.valueOf(ACTIVE_QTY.toString())) {
												is = true;
												break;
											} else {
												is = false;
												break;
											}
										}
									}
									if (is == false) {
										break;
									}
								}
							}
							List<PreWorkPackageMaterialTheoreticalUseQuantity> preWorkPackageMaterialTheoreticalUseQuantitys = null;
							if (is) { // 如果物料满足

								PreWorkPackage PreWorkPackage = new PreWorkPackage();
								PreWorkPackage.setModule_Number(Module);
								PreWorkPackage.setGrade(type);
								PreWorkPackage.setWorkPackageNo(Module + "-" + type);
								PreWorkPackage.setLength_total_ruler(num);

								preWorkPackageMaterialTheoreticalUseQuantitys = new ArrayList<PreWorkPackageMaterialTheoreticalUseQuantity>(
										pipeFittingsMaterials);
								preWorkPackageMaterialTheoreticalUseQuantitys.addAll(material_quantitys);

								String xml = ServiceUtil.createXMLWithLineItemX3(false, XMLHeaderConstants.BP,
										PreWorkPackage.class, MapUtils.java2Map(PreWorkPackage),
										PreWorkPackageMaterialTheoreticalUseQuantity.class,
										MapUtils.java2MapList(preWorkPackageMaterialTheoreticalUseQuantitys),
										PreWorkPackageParts.class, MapUtils.java2MapList(null),
										PreWorkPackageDrawings.class, MapUtils.java2MapList(drawings));

								// 对XML格式化首字母，五个对象均需处理
								xml = XMLResUtil.ResBPExchange(xml, PreWorkPackage.class);
								xml = XMLResUtil.ResBPExchange(xml, PreWorkPackageMaterialTheoreticalUseQuantity.class);
								xml = XMLResUtil.ResBPExchange(xml, PreWorkPackageParts.class);
								xml = XMLResUtil.ResBPExchange(xml, PreWorkPackageDrawings.class);

								BPWebService webservice = new BPWebService();

								String l = webservice.addBPRecordGeneral(projectCode, "Prefabrication Workpackage",
										xml);// 调用原生接口创建JOBc
								// 更新 图纸标识状态，标明该图纸已经对应生成JOBCARD记录
								if (l.equals("Success")) {

									try {
										uxpmStckMapper.UPDATE_bulk_ACTIVE_QTY(
												preWorkPackageMaterialTheoreticalUseQuantitys, projectNumber); // 锁定库存
										uxJbcardMapper.UPDATE_UXJBCARD_PREWorkPackageNo(Module + "-" + type,
												projectNumber, drawings);// 修改Jobcard

									} catch (Exception e) {
										// TODO: handle exception
									}
								}
								num = 0;
								drawings = new ArrayList<PreWorkPackageDrawings>();

							} else {// 结束备料
								break;
							}

						}

					}
				}

			}

		}

	}

	public void auto_SendWorkPackage() {

		List<PreWorkPackage> datas = uxJbcardMapper.select_PreWorkPackage_status("SystemProcessing");// 查出系统正在处理的所有预工作包

		for (PreWorkPackage data : datas) {

			List<PreWorkPackageDrawings> preWorkPackageDrawings = new ArrayList<PreWorkPackageDrawings>();
			List<PreWorkPackageParts> preWorkPackageParts = new ArrayList<PreWorkPackageParts>();
			List<PreWorkPackageMaterialTheoreticalUseQuantity> preWorkPackageMaterialTheoreticalUseQuantitys = new ArrayList<PreWorkPackageMaterialTheoreticalUseQuantity>();

			List<Map<String, Object>> dataLs = uxJbcardMapper.select_PreWorkPackage_Lineitem(data.getId());
			for (Map<String, Object> index : dataLs) {
				System.err.println(index.get("UUU_TAB_ID"));
				if (Integer.valueOf(index.get("UUU_TAB_ID").toString()) == 0) {
					PreWorkPackageDrawings preWorkPackageDrawing = new PreWorkPackageDrawings();
					preWorkPackageDrawing.setDia_Inch(index.get("DIA_INCH").toString());// 焊口直径
					preWorkPackageDrawing.setDrawing_No(index.get("DRAWING_NO").toString());// 图纸编码
					preWorkPackageDrawing.setDrawing_Rev(index.get("DRAWING_REV").toString());//
					// 图纸版本
					preWorkPackageDrawing.setGrade(index.get("GRADE").toString());// 材质
					preWorkPackageDrawings.add(preWorkPackageDrawing);
				} else if (Integer.valueOf(index.get("UUU_TAB_ID").toString()) == 1) {
					PreWorkPackageParts preWorkPackagePart = new PreWorkPackageParts();
					preWorkPackagePart.setDrawing_No(index.get("DRAWING_NO").toString());// spool编码
					preWorkPackagePart.setDrawing_Rev(index.get("DRAWING_REV").toString());
					preWorkPackagePart.setPart_No(index.get("PART_NO").toString());// 零件编码
					preWorkPackagePart.setMaterial_Sort(index.get("MATERIAL_SORT").toString());// 物料类型
					preWorkPackagePart.setPart_Main_Size(index.get("PART_MAIN_SIZE").toString());// 寸劲
					preWorkPackagePart.setLength(index.get("LENGTH").toString());// 长度
					preWorkPackagePart.setGrade(index.get("GRADE").toString());// 材质
					preWorkPackagePart.setMaterial_Code(index.get("MATERIAL_CODE").toString());// 母材编码
					preWorkPackagePart.setMaterial_Long_Desc(index.get("MATERIAL_LONG_DESC").toString());// 长描述
					preWorkPackagePart.setMaterial_Unit(index.get("MATERIAL_UNIT").toString());// 计量单位
					preWorkPackageParts.add(preWorkPackagePart);
				} else if (Integer.valueOf(index.get("UUU_TAB_ID").toString()) == 2) {
					PreWorkPackageMaterialTheoreticalUseQuantity quantity = new PreWorkPackageMaterialTheoreticalUseQuantity();
					quantity.setMaterial_Code(index.get("MATERIAL_CODE").toString());// 母材编码
					// quantity.setMaterial_Long_Desc(index.get("MATERIAL_LONG_DESC").toString());//
					// 长描述
					quantity.setMaterial_Unit(index.get("MATERIAL_UNIT").toString());// 计量单位
					quantity.setQuantity(index.get("QUANTITY").toString());// 数量
					// quantity.setActive_QTY(index.get("ACTIVE_QTY").toString());// 库存可用数量
					preWorkPackageMaterialTheoreticalUseQuantitys.add(quantity);
				}

			}

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", data.getId());
			map.put("Length_total_ruler", data.getLength_total_ruler());
			map.put("WorkPackageNo", data.getWorkPackageNo());
			map.put("parts", preWorkPackageParts);
			map.put("material_quantity", preWorkPackageMaterialTheoreticalUseQuantitys);
			map.put("drawings", preWorkPackageDrawings);
			map.put("moduleNumber", data.getModule_Number());
			map.put("grade", data.getGrade());
			map.put("JobNo", data.getUgenProjectNumber());
			JSONObject jsonObject = JSONObject.fromObject(map);
			System.err.println(jsonObject);

			uxJbcardMapper.UPDATE_UXJBCARD_PREWorkPackageNo(
					data.getModule_Number() + "-" + data.getGrade() + "-" + data.getId(), data.getProject_Id(),
					preWorkPackageDrawings);// 修改Jobcard工作包编号

			doUpload(jsonObject);// 发送给插件

		}

	}

	public void auto_IssuedWorkPackageJobcardAR_Approve() throws RemoteException {

		List<PreWorkPackage> datas = uxJbcardMapper.select_PreWorkPackage_status_StatusV2("SystemProcessing", "N");// 查出系统正在处理的所有预工作包
		for (PreWorkPackage data : datas) {
			List<PreWorkPackageDrawings> preWorkPackageDrawings = new ArrayList<PreWorkPackageDrawings>();
			List<PreWorkPackageParts> preWorkPackageParts = new ArrayList<PreWorkPackageParts>();
			List<PreWorkPackageMaterialTheoreticalUseQuantity> preWorkPackageMaterialTheoreticalUseQuantitys = new ArrayList<PreWorkPackageMaterialTheoreticalUseQuantity>();
			List<Map<String, Object>> dataLs = uxJbcardMapper.select_PreWorkPackage_Lineitem(data.getId());
			for (Map<String, Object> index : dataLs) {
				System.err.println(index.get("UUU_TAB_ID"));
				if (Integer.valueOf(index.get("UUU_TAB_ID").toString()) == 0) {
					PreWorkPackageDrawings preWorkPackageDrawing = new PreWorkPackageDrawings();
					//preWorkPackageDrawing.setDia_Inch(index.get("DIA_INCH").toString());// 焊口直径
					preWorkPackageDrawing.setDrawing_No(index.get("DRAWING_NO").toString());// 图纸编码
					preWorkPackageDrawing.setDrawing_Rev(index.get("DRAWING_REV").toString());// 图纸版本
					preWorkPackageDrawings.add(preWorkPackageDrawing);
				} else if (Integer.valueOf(index.get("UUU_TAB_ID").toString()) == 1) {
					PreWorkPackageParts preWorkPackagePart = new PreWorkPackageParts();
					preWorkPackagePart.setPart_No(index.get("PART_NO").toString());// 零件编码
					preWorkPackagePart.setMaterial_Sort(index.get("MATERIAL_SORT").toString());// 物料类型
					preWorkPackageParts.add(preWorkPackagePart);
				} else if (Integer.valueOf(index.get("UUU_TAB_ID").toString()) == 3) {
					PreWorkPackageMaterialTheoreticalUseQuantity quantity = new PreWorkPackageMaterialTheoreticalUseQuantity();
					quantity.setMaterial_Code(index.get("MATERIAL_CODE").toString());// 母材编码
					quantity.setMaterial_Unit(index.get("MATERIAL_UNIT").toString());// 计量单位
					quantity.setQuantity(index.get("QUANTITY").toString());// 数量
					preWorkPackageMaterialTheoreticalUseQuantitys.add(quantity);
				}

				// 下发相关的 组队焊接Jobcard
				this.auto_GenerateJobcard_PI_CUT(preWorkPackageParts, preWorkPackageMaterialTheoreticalUseQuantitys,
						data.getUgenProjectNumber(), data.getModule_Number(),
						data.getWorkPackageNo() + "-" + data.getId());// 自动生成

				uxJbcardMapper.updateWorkPackageTriggerStatusV2(data.getId().toString(), "Y");// 工作包状态改为已下发

			}
		}

	}

	/**
	 * 根据预工作包生成下切Jobcard
	 *
	 * @param partNos
	 * @param baseMaterialInfos
	 * @param packageName
	 * @param drawingName
	 * @throws RemoteException
	 */
	public void auto_GenerateJobcard_PI_CUT(List<PreWorkPackageParts> preWorkPackageParts,
											List<PreWorkPackageMaterialTheoreticalUseQuantity> preWorkPackageMaterialTheoreticalUseQuantitys,
											String jobNo, String module_Number, String workPackageNo) throws RemoteException {

		JOBCard jobcard = new JOBCard();
		// 3-取BP自带项目信息CODE & NAME
		// 原DRAW包括项目信息，后取消两要素，WEBSERVICE 方法直接输入Project_ID
		Integer projectId = projectInfoMapper.select_ProjectNumber(jobNo);
		if (projectId != null) {

			ProjectShell project = projectInfoMapper.select_ProjectShellDetail(projectId);
			// 赋值JB 编号，对应合同号，业主
			jobcard.setJOBCard_No(jobNo);
			jobcard.setContract_No(project.getContractNo()); // 合同号
			jobcard.setClient(project.getClient());// 客户
			// 赋值JB 模块号，专业，工序，工作车间 ,工作包号
			jobcard.setWork_Package_No(workPackageNo);
			jobcard.setModule_Number(module_Number);
			jobcard.setDiscipline("AR");
			jobcard.setWork_Location(jobcard.getDiscipline() + " Workshop");
			// 更新图纸及版本信息
			jobcard.setJOBCard_No(jobNo);
			jobcard.setDrawing_No(workPackageNo);
			jobcard.setDrawing_Name(workPackageNo);
			jobcard.setDrawing_Version("0");
			jobcard.setPRE_Work_Package_No(workPackageNo);
			// 查询物料库存即时库存数据
			// 根据draw（套料图含图纸编号和版本）找到母材，关联即时库存表进而查询得到
			List<RequiredMaterialDetail> RequiredMaterials = new ArrayList<RequiredMaterialDetail>();

			for (PreWorkPackageMaterialTheoreticalUseQuantity index : preWorkPackageMaterialTheoreticalUseQuantitys) {
				RequiredMaterialDetail RequiredMaterial = new RequiredMaterialDetail();
				RequiredMaterial.setMaterial_Code(index.getMaterial_Code());
				Object object = index.getQuantity();
				RequiredMaterial.setRequire_QTY(Double.valueOf(String.valueOf(object)) + "");
				RequiredMaterials.add(RequiredMaterial);
			}

			jobcard.setMaterial_Status("isReady");
			jobcard.setMaterial_Progress("100%");

			List<MaterialPart> MaterialParts = new ArrayList<MaterialPart>();

			for (PreWorkPackageParts index : preWorkPackageParts) {
				MaterialPart MaterialPart = new MaterialPart();
				MaterialPart.setMaterial_Code(index.getPart_No());
				MaterialParts.add(MaterialPart);
			}

			jobcard.setJOBCard_No(workPackageNo + "AR" + "MAC");
			//jobcard.setJOBCard_No(index.getModule_Name() + "-" + index.getWork_Package_No() + "-ST" + "-MAC");
			jobcard.setWorking_Procedure("cut");// 为jobcard 选定 工序
			if (webservice == null) {
				webservice = new BPWebService();
			}

			// Get HSE Documents
			// 直接根据项目ID和工序查询
			List<JB2HSSE> listHSSEDocuments = null;
			if (jobcard.getWorking_Procedure() != null) {
				listHSSEDocuments = uxJbcardMapper.listJBHSSEDocuments(Integer.valueOf(projectId),
						jobcard.getWorking_Procedure());
				// HSE LIST 大小>0可评估为该文件已经具备
				jobcard.setHSE_Doc_Status("NA");

				if (listHSSEDocuments.size() > 0) {
					jobcard.setHSE_Doc_Status("isReady");
				}
			}
			// Get QCD Documents
			// 直接根据项目ID和工序查询
			List<JB3QCD> listQCDocuments = null;
			if (jobcard.getWorking_Procedure() != null) {
				listQCDocuments = uxJbcardMapper.listJBQCDDocuments(Integer.valueOf(projectId),
						jobcard.getWorking_Procedure());
				// QCD LIST 大小>0可评估为该文件已经具备
				jobcard.setQC_Doc_Status("NA");
				if (listQCDocuments.size() > 0) {
					jobcard.setQC_Doc_Status("isReady");
				}
			}
			// 创建用用于调用原生接口增加JOBCard记录的XML参数
			// createXMLWithLineItemX4 中 X4代码4个页签
			String xml = ServiceUtil.createXMLWithLineItemX4(false, "_bp", JOBCard.class, MapUtils.java2Map(jobcard),
					RequiredMaterialDetail.class, MapUtils.java2MapList(RequiredMaterials), MaterialPart.class,
					MapUtils.java2MapList(MaterialParts), JB2HSSE.class, MapUtils.java2MapList(listHSSEDocuments),
					JB3QCD.class, MapUtils.java2MapList(listQCDocuments)

			);
			// 对XML格式化首字母，五个对象均需处理
			xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
			xml = XMLResUtil.ResBPExchange(xml, RequiredMaterialDetail.class);
			xml = XMLResUtil.ResBPExchange(xml, MaterialPart.class);
			xml = XMLResUtil.ResBPExchange(xml, JB2HSSE.class);
			xml = XMLResUtil.ResBPExchange(xml, JB3QCD.class);
			System.out.println(xml);
			String l = webservice.addBPRecordGeneral(project.getProjectNumber(), "JOBCard List", xml);// 调用原生接口创建JOBc
			// 更新 图纸标识状态，标明该图纸已经对应生成JOBCARD记录
			System.err.println(l);

			JOBCard jobcard2 = new JOBCard();
			List<String> recordNos = uxJbcardMapper.slect_Jbcard_recordNo(workPackageNo, projectId); // 查询可下发的所有Jobcard
			// 记录ID
			for (String data : recordNos) {
				jobcard.setRecord_no(data); // jobcard 的记录ID 查出所有料满足的 jobcard
				String xml2 = ServiceUtil.createXML(false, XMLHeaderConstants.BP, JOBCard.class,
						MapUtils.java2Map(jobcard2));
				xml2 = XMLResUtil.ResBPExchange(xml, JOBCard.class);
				UnifierWebServicesUfbs service = new UnifierWebServicesUfbs();
				// WFCurrentStepName 是目前工作流节点
				// WFActionName 是执行操作
				String oprionsXml = " <options><WFCurrentStepName>Discipline Engineer Check</WFCurrentStepName>"
						+ "<WFActionName>Auto Completed</WFActionName></options>";
				System.err
						.println(this.processResult(service.updateBPRecordV2(jobNo, "JOBCard List", xml2, oprionsXml)));
			}

		}
	}

	/**
	 * 处理插件返回的工作包
	 */
	public void update_WorkPackageAR(JSONObject param) {

		List<Map<String, String>> freedMaps = new ArrayList<Map<String, String>>(); // 需要释放的物料
		List<Map<String, String>> increaseMaps = new ArrayList<Map<String, String>>(); // 需要 添加的物料

		List<Map<String, String>> theoreticalUseQuantitys = (List<Map<String, String>>) param.get("material_quantity");// 理论使用母材数量
		List<Map<String, String>> actualUseQuantitys = (List<Map<String, String>>) param.get("baseMaterials_quantity");// 实际使用母材数量

		for (Map<String, String> data : theoreticalUseQuantitys) {
			for (Map<String, String> data2 : actualUseQuantitys) {
				if (data.get("material_Code").equals(data2.get("material_Code"))) {
					Object Object1 = data.get("quantity");
					Object Object2 = data2.get("quantity");
					double quantityData = Double.valueOf(Object1.toString());
					double quantityData2 = Double.valueOf(Object2.toString());
					if (quantityData > quantityData2) {
						Map<String, String> freedMap = new HashMap<String, String>();
						freedMap.put("material_Code", data.get("material_Code"));
						freedMap.put("quantity", String.valueOf(quantityData - quantityData2));
						freedMaps.add(freedMap);
					} else if (quantityData < quantityData2) {
						Map<String, String> increaseMap = new HashMap<String, String>();
						increaseMap.put("material_Code", data.get("material_Code"));
						increaseMap.put("quantity", String.valueOf(quantityData2 - quantityData));
						increaseMaps.add(increaseMap);
					}
					break;
				}
			}
		}

		Integer projectNumber = projectInfoMapper.select_ProjectNumber(param.get("JobNo").toString());
		String status = uxJbcardMapper.select_WorkPackageTriggerStatusV2("47");

		if (status == null) {
			uxJbcardMapper.insert_uxjobpw_lieitem(actualUseQuantitys, Integer.valueOf(param.get("id").toString()),
					uxJbcardMapper.select_uxjobpw_lieitem_MaxID(), 3);// 为预工作包添加实际使用物料
		}

		if (increaseMaps.size() > 0) {
			uxpmStckMapper.UPDATE_bulk_ACTIVE_QTY_Maps(increaseMaps, projectNumber); // 锁定库存
		}
		if (freedMaps.size() > 0) {
			uxpmStckMapper.UPDATE_bulk_ACTIVE_QTY_Freed_Maps(freedMaps, projectNumber); // 释放库存
		}

		uxJbcardMapper.updateWorkPackageTriggerStatusV2(param.get("id").toString(), "N");// 工作包状态改为已返回

	}

	/**
	 * 自动下发某工作包下的所有JOBcard
	 *
	 * @param datas
	 * @param packageName
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	public void auto_IssuedJobcardAR_Approve(List<String> datas, String packageName) throws IOException {
		BPWebService webservice = new BPWebService();
		JOBCard jobcard = new JOBCard();
		List<String> recordNos = uxJbcardMapper.slect_Jbcard_recordNo(packageName, 1014); // 查询可下发的所有Jobcard 记录ID
		for (String data : recordNos) {
			jobcard.setRecord_no(data); // jobcard 的记录ID 查出所有料满足的 jobcard
			String xml = ServiceUtil.createXML(false, XMLHeaderConstants.BP, JOBCard.class, MapUtils.java2Map(jobcard));
			xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
			System.err.println(xml);
			UnifierWebServicesUfbs service = new UnifierWebServicesUfbs();
			// WFCurrentStepName 是目前工作流节点
			// WFActionName 是执行操作
			String oprionsXml = " <options><WFCurrentStepName>Discipline Engineer Check</WFCurrentStepName>"
					+ "<WFActionName>Auto Completed</WFActionName></options>";
			System.err
					.println(this.processResult(service.updateBPRecordV2("TBJN0149", "JOBCard List", xml, oprionsXml)));
		}
	}

	/**
	 * 自动为优先级中的构件进行备料，如构件的套料未进行下发则也为其进行备料
	 *
	 * @throws IOException
	 */
	public void auto_IssuedJobcardAR() throws IOException {
		JOBCard jobcard = new JOBCard();

		List<Map<String, String>> projectInfoMaps = projectInfoMapper.select_ProjectID_Number(); // 查找出所有项目

		for (Map<String, String> projectInfoMap : projectInfoMaps) { // 遍历项目

			Object object = projectInfoMap.get("PID");
			int projectId = Integer.parseInt(String.valueOf(object));
			List<Integer> MaterPri1s = uxJbcardMapper.selectJobcardPriority_MaterPri(projectId, "uxmppof"); // 查出第一序列备料优先级
			boolean is = false; // 用于判断是否开启后续大组的备料
			for (Integer MaterPri1 : MaterPri1s) { // 循环第一序列
				List<Map<String, String>> datas = uxJbcardMapper
						.selectjobcard_MaterialPreparationAR_fabrication(projectId, MaterPri1);// 查出所有未下发的Jobacrd
				for (Map<String, String> data : datas) {// 遍历序列中的备料单

					if (data.get("DRAWING_NO") == null || data.get("JOBC_RECORD_NO") == null) {
						// 无图纸信息或无预Jobcard 则结束此序列备料
						if (is == false) {
							is = true;
						}
						continue;
					}

					if (data.get("MATERIAL_STATUS").equals("NOK")) {// 如果未备料
						// 查询图纸所需母材
						List<Map<String, String>> parts = uxJbcardMapper
								.selectjobcard_MaterialPreparationAR_bulk(projectId, data.get("DRAWING_NO"),
										data.get("REV"));

						List<String> partNos = new ArrayList<String>();

						for (Map<String, String> index : parts) {
							Object NO = index.get("NO"); // BigDecimal 要先转为Object
							int projectNO = Integer.parseInt(String.valueOf(NO));
							if (projectNO > 0) { // 如果齐全则往下备料
								partNos.add(index.get("MATERIAL_CODE"));//收集无库存的零件编码
							}
						}

						if (partNos.size() == 0) {// 母材库存不满足
								boolean bulkis = true;
								List<Map<String, String>> bulks =null;

		jobcard.setRecord_no(data.get("JOBC_RECORD_NO"));
							String xml = ServiceUtil.createXML(false, XMLHeaderConstants.BP, JOBCard.class,
									MapUtils.java2Map(jobcard));
							xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
							UnifierWebServicesUfbs UnifierWebServicesUDF = new UnifierWebServicesUfbs();

							String oprionsXml = " <options><WFCurrentStepName>Discipline Engineer Check</WFCurrentStepName>"
									+ "<WFActionName>Material Preparation Completed</WFActionName></options>";
							// WFCurrentStepName 当前步骤名称 WFActionName执行的操作名称

							String mgs = this.processResult(UnifierWebServicesUDF.updateBPRecordV2(
									projectInfoMap.get("PROJECTNUMBER"), "JOBCard List", xml, oprionsXml));
							System.err.println(mgs);
							if(parts !=null){
								if (mgs.equals("Success")) { // 工作流推送成功则进行物料锁定
									uxJbcardMapper.update_UXJBCARD_MATERIAL_STATUS2(data.get("JOBC_RECORD_NO")); // 修改jobcard状态
									uxpmStckMapper.updateUxpmStckTotal(parts);// 锁定库存
								} else if (mgs.equals("Failed, WFCurrentStepName is not correct.")) {
									uxJbcardMapper.update_UXJBCARD_MATERIAL_STATUS2(data.get("JOBC_RECORD_NO")); // 修改jobcard状态
									uxpmStckMapper.updateUxpmStckTotal(parts);// 锁定库存
								} else {
									if (is == false) {
										is = true;
									}
									continue; // 结束此序列的备料（第一序列）
								}
							}
						}


					}

				}

				if (is) {// 如果次序列中有构件未成功备料 未生成备料单则停止别的 第一序列备料
					break;
				}
			}
		}
	}
	// 自动审批图纸
	@SuppressWarnings("unused")
	public void auto_IssuedJobcardAR_Approve2() throws IOException {
		UnifierWebServicesUfbs service = new UnifierWebServicesUfbs();
		Drawing Drawing = new Drawing();
		List<String> datas = uxenglstMapper.selectUxenglst_Pending(1014,"AR");
		for (String data : datas) {
			Drawing.setRecord_no(data); // jobcard 的记录ID 查出所有料满足的 jobcard
			String xml = ServiceUtil.createXML(false, XMLHeaderConstants.BP, Drawing.class, MapUtils.java2Map(Drawing));
			xml = XMLResUtil.ResBPExchange(xml, Drawing.class);
			System.err.println(xml);
			String oprionsXml = " <options><WFCurrentStepName>Check By</WFCurrentStepName>"
					+ "<WFActionName>Agree</WFActionName></options>";
			System.err
					.println(this.processResult(service.updateBPRecordV2("TBJN0149", "Drawing List", xml, oprionsXml)));

		}

	}

	public static void main(String[] args) throws IOException {
		AutoJobcArdPIServerImpl AutoJobcArdServerImpl = new AutoJobcArdPIServerImpl();
		AutoJobcArdServerImpl.auto_IssuedJobcardPI_Approve2(); // 自动审批图纸
		// AutoJobcArdServerImpl.auto_GenerateJobcard_PI();
		// AutoJobcArdServerImpl.auto_synchro_UXMMT_PI();
		AutoJobcArdServerImpl.auto_PreWorkPackagePI();

	}

}
